<template>
  <view class="drift-bottle-container">
    <!-- 头部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="title">漂流瓶</view>
      <view class="placeholder"></view>
    </view>

    <!-- 海洋背景 -->
    <view class="ocean-background">
      <!-- 波浪动画 -->
      <view class="wave wave1"></view>
      <view class="wave wave2"></view>
      <view class="wave wave3"></view>
      
      <!-- 漂浮的漂流瓶 -->
      <view class="floating-bottles">
        <view 
          class="bottle" 
          v-for="(bottle, index) in floatingBottles" 
          :key="index"
          :style="{ left: bottle.left, top: bottle.top, animationDelay: bottle.delay }"
          @click="pickBottle"
        >
          🍾
        </view>
      </view>
      
      <!-- 主要操作区域 -->
      <view class="main-actions">
        <view class="action-card throw-card" @click="showThrowModal">
          <view class="action-icon">🚀</view>
          <view class="action-title">扔漂流瓶</view>
          <view class="action-desc">写下你的心情，投入大海</view>
        </view>
        
        <view class="action-card pick-card" @click="pickBottle">
          <view class="action-icon">🎣</view>
          <view class="action-title">捡漂流瓶</view>
          <view class="action-desc">看看谁的故事漂到了你身边</view>
        </view>
      </view>
    </view>

    <!-- 扔漂流瓶弹窗 -->
    <view class="modal-overlay" v-if="showThrow" @click="hideThrowModal">
      <view class="modal-content throw-modal" @click.stop>
        <view class="modal-header">
          <view class="modal-title">扔出漂流瓶</view>
          <view class="modal-close" @click="hideThrowModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="modal-body">
          <textarea 
            class="bottle-input" 
            v-model="throwContent" 
            placeholder="写下你想说的话...\n\n也许会有人在远方收到你的心情" 
            :maxlength="500"
            auto-height
          />
          <view class="char-count">
            <text class="count-text" :class="{ 'warning': throwContent.length > 450 }">
              {{ throwContent.length }}/500
            </text>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="hideThrowModal">
            <text class="btn-text">取消</text>
          </view>
          <view class="confirm-btn" :class="{ 'disabled': !canThrow || isThrowLoading }" @click="throwBottle">
            <text class="btn-text">{{ isThrowLoading ? '发送中...' : '扔出去' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 捡漂流瓶弹窗 -->
    <view class="modal-overlay" v-if="showPick" @click="hidePickModal">
      <view class="modal-content pick-modal" @click.stop>
        <view class="modal-header">
          <view class="modal-title">你捡到了一个漂流瓶</view>
          <view class="modal-close" @click="hidePickModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="modal-body">
          <view class="bottle-info">
            <view class="user-info">
              <image class="user-avatar" :src="pickedBottle.userAvatar" mode="aspectFill" />
              <view class="user-details">
                <text class="user-name">{{ pickedBottle.userName }}</text>
                <text class="bottle-time">{{ pickedBottle.time }}</text>
              </view>
            </view>
            <view class="bottle-content">
              <text class="content-text">{{ pickedBottle.content }}</text>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="close-btn" @click="hidePickModal">
            <text class="btn-text">关闭</text>
          </view>
          <view class="add-friend-btn" @click="addFriend">
            <text class="btn-text">添加好友</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { DriftBottleAPI, ContactAPI } from '@/utils/api'

// 响应式数据
const showThrow = ref(false)
const showPick = ref(false)
const throwContent = ref('')

// 漂浮的漂流瓶数据
const floatingBottles = ref([
  { left: '10%', top: '30%', delay: '0s' },
  { left: '70%', top: '25%', delay: '2s' },
  { left: '30%', top: '45%', delay: '4s' },
  { left: '80%', top: '50%', delay: '1s' },
  { left: '15%', top: '60%', delay: '3s' },
  { left: '60%', top: '70%', delay: '5s' }
])

// 捡到的漂流瓶数据
const pickedBottle = ref({
  userName: '',
  userAvatar: '',
  content: '',
  time: '',
  userId: '',
  email: ''
})

// 加载状态
const isThrowLoading = ref(false)
const isPickLoading = ref(false)

// 计算属性
const canThrow = computed(() => {
  const content = throwContent.value.trim()
  return content.length > 0 && content.length <= 500
})

// 方法
const goBack = () => {
   uni.switchTab({
    url: '/pages/message'
  })
}

const showThrowModal = () => {
  showThrow.value = true
}

const hideThrowModal = () => {
  showThrow.value = false
  throwContent.value = ''
}

const throwBottle = async () => {
  if (!canThrow.value || isThrowLoading.value) return
  
  try {
    isThrowLoading.value = true
    
    const content = throwContent.value.trim()
    
    // 验证内容长度
    if (content.length === 0) {
      uni.showToast({
        title: '请输入漂流瓶内容',
        icon: 'none'
      })
      return
    }
    
    if (content.length > 500) {
      uni.showToast({
        title: '内容不能超过500个字符',
        icon: 'none'
      })
      return
    }
    
    const response = await DriftBottleAPI.throwBottle(content)
    
    // 根据API文档，成功响应的结构是 { success: true, message: string, data: object }
    if (response.code === 200 || response.code === 200) {
      uni.showToast({
        title: response.message || '漂流瓶已扔出',
        icon: 'success'
      })
      hideThrowModal()
    } else {
      throw new Error(response.message || '发送失败')
    }
  } catch (error: any) {
    console.error('扔漂流瓶失败:', error)
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none'
    })
  } finally {
    isThrowLoading.value = false
  }
}

const pickBottle = async () => {
  if (isPickLoading.value) return
  
  try {
    isPickLoading.value = true
    
    uni.showLoading({
      title: '正在捡漂流瓶...'
    })
    
    const response = await DriftBottleAPI.pickBottle()
    
    uni.hideLoading()
    
    // 根据API文档，成功响应的结构是 { success: true, message: string, data: object }
    if ((response.code === 200 || response.code === 200) && response.data) {
      const bottle = response.data
      pickedBottle.value = {
        userName: bottle.sender.nickName,
        userAvatar: bottle.sender.avatar || 'https://picsum.photos/100/100?random=1',
        content: bottle.content,
        time: formatTime(bottle.createdAt),
        userId: bottle.sender.userId,
        email: bottle.sender.email
      }
      showPick.value = true
    } else {
      throw new Error(response.message || '暂时没有可捡起的漂流瓶，请稍后再试')
    }
  } catch (error: any) {
    console.error('捡漂流瓶失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '暂时没有可捡起的漂流瓶',
      icon: 'none'
    })
  } finally {
    isPickLoading.value = false
  }
}

const hidePickModal = () => {
  showPick.value = false
}

const addFriend = async () => {
  if (!pickedBottle.value.email) {
    uni.showToast({
      title: '无法获取用户信息',
      icon: 'none'
    })
    return
  }

  // 先隐藏漂流瓶弹窗，避免z-index层级问题
  const tempBottleData = { ...pickedBottle.value }
  hidePickModal()
  
  // 延迟一下确保弹窗完全隐藏
  setTimeout(() => {
    uni.showModal({
      title: '添加好友',
      content: `确定要向 ${tempBottleData.userName} 发送好友申请吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            // 显示加载提示
            uni.showLoading({
              title: '发送中...'
            })
            
            // 调用发送好友申请的API
            const response = await ContactAPI.sendFriendRequest(tempBottleData.email, '通过漂流瓶认识，希望能成为好友')
            
            uni.hideLoading()
            
            if (response.code === 200) {
              uni.showToast({
                title: '好友申请已发送',
                icon: 'success'
              })
            } else {
              throw new Error(response.message || '发送失败')
            }
          } catch (error: any) {
            uni.hideLoading()
            console.error('发送好友申请失败:', error)
            
            // 根据错误信息显示不同的提示
            if (error.message?.includes('已经是好友')) {
              uni.showToast({
                title: '你们已经是好友了',
                icon: 'none'
              })
            } else if (error.message?.includes('已发送')) {
              uni.showToast({
                title: '好友申请已发送过',
                icon: 'none'
              })
            } else if (error.message?.includes('不能添加自己')) {
              uni.showToast({
                title: '不能添加自己为好友',
                icon: 'none'
              })
            } else {
              uni.showToast({
                title: error.message || '发送失败，请重试',
                icon: 'none'
              })
            }
          }
        }
      }
    })
  }, 100)
}

// 时间格式化函数
const formatTime = (timeString: string) => {
  const now = new Date()
  const time = new Date(timeString)
  const diff = now.getTime() - time.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return time.toLocaleDateString()
  }
}

onMounted(() => {
  // 页面加载完成
})
</script>

<style scoped>
.drift-bottle-container {
  height: 100vh;
  background: linear-gradient(180deg, #87CEEB 0%, #4682B4 50%, #191970 100%);
  position: relative;
  overflow: hidden;
}

/* 头部样式 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: calc(120rpx + env(safe-area-inset-top));
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: env(safe-area-inset-top) 30rpx 0;
  z-index: 100;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.2);
}

.back-icon {
  font-size: 36rpx;
  color: #ffffff;
  font-weight: bold;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
}

.placeholder {
  width: 60rpx;
}

/* 海洋背景 */
.ocean-background {
  height: 100vh;
  position: relative;
  padding-top: calc(140rpx + env(safe-area-inset-top));
}

/* 波浪动画 */
.wave {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 200%;
  height: 200rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: wave 6s ease-in-out infinite;
}

.wave1 {
  animation-delay: 0s;
}

.wave2 {
  animation-delay: 2s;
  opacity: 0.7;
}

.wave3 {
  animation-delay: 4s;
  opacity: 0.5;
}

@keyframes wave {
  0%, 100% {
    transform: translateX(-50%) translateY(0);
  }
  50% {
    transform: translateX(-50%) translateY(-20rpx);
  }
}

/* 漂浮的漂流瓶 */
.floating-bottles {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.bottle {
  position: absolute;
  font-size: 60rpx;
  animation: float 4s ease-in-out infinite;
  pointer-events: auto;
  cursor: pointer;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20rpx) rotate(5deg);
  }
}

/* 主要操作区域 */
.main-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 300rpx);
  gap: 60rpx;
  padding: 0 60rpx;
}

.action-card {
  width: 100%;
  max-width: 500rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.action-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.action-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 15rpx;
}

.action-desc {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.5;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 600rpx;
  background: #ffffff;
  border-radius: 30rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background: #f5f5f5;
}

.close-icon {
  font-size: 30rpx;
  color: #666666;
}

.modal-body {
  padding: 40rpx 30rpx;
}

/* 扔漂流瓶弹窗 */
.bottle-input {
  width: 100%;
  min-height: 300rpx;
  font-size: 30rpx;
  color: #333333;
  line-height: 1.6;
  border: 2rpx solid #e5e5e5;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background: #fafafa;
  box-sizing: border-box;
}

.char-count {
  text-align: right;
  margin-bottom: 20rpx;
}

.count-text {
  font-size: 24rpx;
  color: #999999;
}

.count-text.warning {
  color: #ff4757;
}

/* 捡漂流瓶弹窗 */
.bottle-info {
  text-align: center;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.user-details {
  flex: 1;
  text-align: left;
}

.user-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333333;
  display: block;
  margin-bottom: 8rpx;
}

.bottle-time {
  font-size: 24rpx;
  color: #999999;
}

.bottle-content {
  background: #ffffff;
  border: 2rpx solid #e5e5e5;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-top: 20rpx;
}

.content-text {
  font-size: 30rpx;
  color: #333333;
  line-height: 1.6;
  text-align: left;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 弹窗底部 */
.modal-footer {
  display: flex;
  border-top: 1rpx solid #e5e5e5;
}

.cancel-btn,
.confirm-btn,
.close-btn,
.add-friend-btn {
  flex: 1;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn,
.close-btn {
  border-right: 1rpx solid #e5e5e5;
}

.confirm-btn,
.add-friend-btn {
  background: #007AFF;
}

.confirm-btn.disabled {
  background: #cccccc;
}

.btn-text {
  font-size: 30rpx;
  color: #666666;
}

.confirm-btn .btn-text,
.add-friend-btn .btn-text {
  color: #ffffff;
}
</style>